<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>申请管理</span>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="学生姓名">
        <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="学年">
        <el-date-picker
            v-model="queryParams.academicYear"
            type="year"
            placeholder="选择学年"
            clearable
            style="width: 150px"
            value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
          <el-option label="拒绝" :value="0" />
          <el-option label="辅导员审核" :value="1" />
          <el-option label="学院审核" :value="2" />
          <el-option label="学校审核" :value="3" />
          <el-option label="通过" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="学院">
        <el-select v-model="queryParams.collegeId" placeholder="请选择学院" clearable style="width: 200px">
          <el-option 
            v-for="college in collegeList" 
            :key="college.id" 
            :label="college.realName" 
            :value="college.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="困难等级">
        <el-select v-model="queryParams.difficultyLevel" placeholder="请选择等级" clearable style="width: 150px">
          <el-option label="一般困难" :value="1" />
          <el-option label="困难" :value="2" />
          <el-option label="特别困难" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="success" @click="handleAdd">新增申请</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        v-loading="loading"
        border
    >
      <el-table-column prop="studentName" label="学生姓名" align="center" header-align="center" width="120" />
      <el-table-column label="学年" align="center" header-align="center" width="130">
        <template #default="scope">
          {{ formatAcademicYear(scope.row.academicYear) }}
        </template>
      </el-table-column>
      <el-table-column prop="college" label="学院" align="center" header-align="center" min-width="150" />
      <el-table-column prop="counselor" label="辅导员" align="center" header-align="center" width="120" />
      <el-table-column label="困难等级" align="center" header-align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" header-align="center" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">拒绝</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">辅导员审核</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="warning">学院审核</el-tag>
          <el-tag v-else-if="scope.row.status === 3" type="warning">学校审核</el-tag>
          <el-tag v-else-if="scope.row.status === 4" type="success">通过</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" align="center" header-align="center" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.applyTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)">查看详情</el-button>
          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.limit"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        @update:current-page="(val) => queryParams.page = val"
        @update:page-size="(val) => queryParams.limit = val"
        style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="申请详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学生姓名">{{ detailData.studentName }}</el-descriptions-item>
        <el-descriptions-item label="学年">{{ formatAcademicYear(detailData.academicYear) }}</el-descriptions-item>
        <el-descriptions-item label="学院" :span="2">{{ detailData.college }}</el-descriptions-item>
        <el-descriptions-item label="辅导员">{{ detailData.counselor }}</el-descriptions-item>
        <el-descriptions-item label="困难等级">
          <el-tag v-if="detailData.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请状态" :span="2">
          <el-tag v-if="detailData.status === 0" type="danger">拒绝</el-tag>
          <el-tag v-else-if="detailData.status === 1" type="warning">辅导员审核</el-tag>
          <el-tag v-else-if="detailData.status === 2" type="warning">学院审核</el-tag>
          <el-tag v-else-if="detailData.status === 3" type="warning">学校审核</el-tag>
          <el-tag v-else-if="detailData.status === 4" type="success">通过</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间" :span="2">
          {{ formatDateTime(detailData.applyTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请原因" :span="2">
          <div class="reason-text">{{ detailData.applyReason || '-' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="拒绝原因" :span="2" v-if="detailData.rejectedReason">
          <div class="reason-text rejected">{{ detailData.rejectedReason }}</div>
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button type="primary" @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editVisible" title="编辑申请" width="600px">
      <el-form :model="editForm" label-width="120px" ref="editFormRef" :rules="editRules">
        <el-form-item label="申请状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="拒绝" :value="0" />
            <el-option label="辅导员审核" :value="1" />
            <el-option label="学院审核" :value="2" />
            <el-option label="学校审核" :value="3" />
            <el-option label="通过" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请原因" prop="applyReason">
          <el-input
              v-model="editForm.applyReason"
              type="textarea"
              :rows="4"
              placeholder="请输入申请原因"
          />
        </el-form-item>
        <el-form-item label="拒绝原因" v-if="editForm.status === 0">
          <el-input
              v-model="editForm.rejectedReason"
              type="textarea"
              :rows="3"
              placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { _getApplicationList, _deleteApplication, _getApplicationById, _updateApplication } from '@/api/application'
import { _getUserByRole } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

// 查询条件
const queryParams = ref({
  page: 1,
  limit: 10,
  studentName: '',
  academicYear: '',
  collegeId: null,
  status: null,
  difficultyLevel: null
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 学院列表
const collegeList = ref([])

// 详情对话框
const detailVisible = ref(false)
const detailData = ref({})

// 编辑对话框
const editVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: null,
  studentId: null,
  batchId: null,
  applyReason: '',
  status: null,
  rejectedReason: ''
})

// 编辑表单验证规则
const editRules = {
  status: [
    { required: true, message: '请选择申请状态', trigger: 'change' }
  ],
  applyReason: [
    { required: true, message: '请输入申请原因', trigger: 'blur' }
  ]
}

// 格式化学年（2024 -> 2024-2025）
const formatAcademicYear = (year) => {
  if (!year) return '-'
  return `${year}-${year + 1}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取学院列表
const getCollegeList = () => {
  _getUserByRole().then(res => {
    if (res.code === 200) {
      collegeList.value = res.data.userList || []
    } else {
      ElMessage.error(res.message || '获取学院列表失败')
    }
  }).catch(err => {
    console.error('获取学院列表失败:', err)
    ElMessage.error('获取学院列表失败')
  })
}

// 查询列表
const getList = () => {
  loading.value = true
  _getApplicationList(queryParams.value).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch(err => {
    console.error('查询失败:', err)
    ElMessage.error('查询失败')
  }).finally(() => {
    loading.value = false
  })
}

// 查询按钮
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    studentName: '',
    academicYear: '',
    collegeId: null,
    status: null,
    difficultyLevel: null
  }
  getList()
}

// 新增申请按钮
const handleAdd = () => {
  router.push('/application/form')
}

// 查看详情按钮
const handleDetail = (row) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

// 编辑按钮
const handleEdit = (row) => {
  loading.value = true
  _getApplicationById(row.id).then(res => {
    if (res.code === 200) {
      const data = res.data.application
      editForm.value = {
        id: data.id,
        studentId: data.studentId,
        batchId: data.batchId,
        applyReason: data.applyReason || '',
        status: data.status,
        rejectedReason: data.rejectedReason || ''
      }
      editVisible.value = true
      // 清空表单验证
      if (editFormRef.value) {
        editFormRef.value.clearValidate()
      }
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  }).catch(err => {
    console.error('获取详情失败:', err)
    ElMessage.error('获取数据失败')
  }).finally(() => {
    loading.value = false
  })
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确认删除学生 "${row.studentName}" 的申请吗？`,
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    _deleteApplication(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(err => {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交编辑
const submitEdit = () => {
  editFormRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        id: editForm.value.id,
        studentId: editForm.value.studentId,
        batchId: editForm.value.batchId,
        applyReason: editForm.value.applyReason,
        status: editForm.value.status
      }
      
      // 只有状态为拒绝时才提交拒绝原因
      if (editForm.value.status === 0 && editForm.value.rejectedReason) {
        submitData.rejectedReason = editForm.value.rejectedReason
      }
      
      _updateApplication(submitData).then(res => {
        if (res.code === 200) {
          ElMessage.success('更新成功')
          editVisible.value = false
          getList()
        } else {
          ElMessage.error(res.message || '更新失败')
        }
      }).catch(err => {
        console.error('更新失败:', err)
        ElMessage.error('更新失败')
      })
    }
  })
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  getList()
}

const handleSizeChange = (size) => {
  queryParams.value.limit = size
  queryParams.value.page = 1
  getList()
}

// 初始化
onMounted(() => {
  getCollegeList()
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .query-form {
    margin-bottom: 20px;
  }
}

.reason-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  
  &.rejected {
    color: #f56c6c;
  }
}
</style>

